/*
 * This file is an example of how to embed web-server functionality
 * into existing application.
 * Compilation line:
 * cc example.c shttpd.c -DEMBEDDED
 */

#ifdef _WIN32
#include <winsock.h>
#define	snprintf			_snprintf
#pragma comment(lib,"ws2_32")
#else
#include <sys/types.h>
#include <sys/select.h>
#endif

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#include "shttpd.h"

static int
index_html(struct shttpd_callback_arg *arg)
{
	int		n = 0;
	int		*p = arg->callback_data; /* integer passed to us */
	const char	*value;

	/* Change the value of integer variable */
	if ((value = shttpd_get_var(arg->connection, "name1")) != NULL)
		*p = atoi(value);
	

	n += snprintf(arg->buf + n, arg->buflen - n, "%s",
	    "HTTP/1.1 200 OK\r\n"
	    "Content-Type: text/html\r\n"
	    "\r\n"
	    "<html><body>");
	
	n += snprintf(arg->buf + n, arg->buflen - n,
	    "<p>Variable value: [%d]</p>", *p);
	
	n += snprintf(arg->buf + n, arg->buflen - n, "%s",
	    "<form method=\"get\">"
	    "Enter new value: "
	    "<input type=\"text\" name=\"name1\"/>"
	    "<input type=\"submit\">"
	    "</form>"
	    "<p><a href=\"/secret\">protected page</a> (guest:guest)</p> "
	    "<p><a href=\"/template\">template-generated page</a></p>"
	    "</body></html>");

	return (n);
}

static int
template_html(struct shttpd_callback_arg *arg)
{
	int	n;

	n = shttpd_template(arg->connection,
	    "Content-Type: text/html\r\n","template.html",
	    "KEYWORD1", "Substitution 1",
	    "KEYWORD2", "Substitution 2", NULL);

	return (n);
}

static int
secret_html(struct shttpd_callback_arg *arg)
{
	int		n = 0;

	n = snprintf(arg->buf, arg->buflen, "%s",
	    "HTTP/1.1 200 OK\r\n"
	    "Content-Type: text/html\r\n"
	    "\r\n"
	    "<html><body><p>This is a protected page</body></html>");
	
	return (n);
}

int main(int argc, char *argv[])
{
	int		sock, data = 1234567;
	
	/* Get rid of warnings */
	argc = argc;
	argv = argv;
	
	/* Initialize and setup URLs we gonna serve */
	shttpd_init(NULL);

	/* Let pass 'data' variable to callback, user can change it */
	shttpd_register_url("/", &index_html, (void *) &data);

	/* Show how to use generation from template */
	shttpd_register_url("/template", &template_html, NULL);

	/* Show how to use password protection */
	shttpd_register_url("/secret", &secret_html, (void *) &data);
	shttpd_protect_url("/secret", "passfile");

	/* Open listening socket */
	sock = shttpd_open_port(9000);

	/* Serve connections infinitely until someone kills us */
	for (;;)
		shttpd_poll(sock, 200);

	/* Probably unreached, because we will be killed by signal */
	shttpd_fini();

	return (EXIT_SUCCESS);
}
